package com.nuoniu.sibanyun.service.so.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microsoft.schemas.office.visio.x2012.main.CellType;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.dto.BarcodeMainInfoSearchDto;
import com.nuoniu.sibanyun.entity.dto.InInventorySaveDto;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.erp.ErpProcessRoute;
import com.nuoniu.sibanyun.entity.erp.ErpProject;
import com.nuoniu.sibanyun.entity.erp.barcode.ErpBarcodeMainInfo;
import com.nuoniu.sibanyun.entity.erp.barcode.vo.BarcodeInOutStatisticVo;
import com.nuoniu.sibanyun.entity.erp.in.InInventory;
import com.nuoniu.sibanyun.entity.so.VAreaCalculationDetail;
import com.nuoniu.sibanyun.entity.so.VAreaCalculationMain;
import com.nuoniu.sibanyun.entity.vo.ns_staristics.ProjectBatchExecutionStatisticsVo;
import com.nuoniu.sibanyun.entity.vo.ns_staristics.ProjectExecutionStatisticsVo;
import com.nuoniu.sibanyun.entity.vo.ns_staristics.dto.ProjectExecutionStatisticsDto;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.mapper.so.VAreaCalculationMainMapper;
import com.nuoniu.sibanyun.service.ISysUserService;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsService;
import com.nuoniu.sibanyun.service.erp.*;
import com.nuoniu.sibanyun.service.erp.barcode.IErpBarcodeInOutService;
import com.nuoniu.sibanyun.service.erp.barcode.IErpBarcodeMainInfoService;
import com.nuoniu.sibanyun.service.erp.in.IInInventoryService;
import com.nuoniu.sibanyun.service.so.IVAreaCalculationDetailService;
import com.nuoniu.sibanyun.service.so.IVAreaCalculationMainService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.ExcelUtils;
import com.twelvemonkeys.util.LinkedSet;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 面积计算-主表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-10-22
 */
@Service
@Log4j2
public class VAreaCalculationMainServiceImpl extends ServiceImpl<VAreaCalculationMainMapper, VAreaCalculationMain> implements IVAreaCalculationMainService {

    @Autowired
    private IVAreaCalculationDetailService areaCalculationDetailService;
    @Autowired
    private ICrmGoodsService crmGoodsService;
    @Autowired
    private IErpAccountService erpAccountService;
    @Autowired
    private ErpNumberSetMapper numberSetMapper;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IInInventoryService inInventoryService;
    @Autowired
    private IErpProjectService projectService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IErpBarcodeMainInfoService barcodeMainInfoService;
    @Autowired
    private IErpVoucherDesignService erpVoucherDesignService;
    @Autowired
    private IErpProcessRouteService erpProcessRouteService;

    @Autowired
    private IErpBarcodeInOutService barcodeInOutService;



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveAreaCalculationMain(VAreaCalculationMain areaCalculationMain) {
        Long mainId = areaCalculationMain.getId();
        List<VAreaCalculationDetail> orderDetailList = areaCalculationMain.getOrderDetailList();
        if(null == orderDetailList)throw new NuoNiuException("单据明细不能为空");
        UserInfo userInfo = UserThreadLocal.get();
        VAreaCalculationMain oldVAreaCalculationMain =null;
        if(mainId != null) {
            //校验详情（详情不能有其他单据的明细ID）
            boolean isHaveErrorId = orderDetailList.stream().anyMatch(f -> null != f.getOrderId() && !mainId.toString().equals(f.getOrderId().toString()));
            if(isHaveErrorId)throw new NuoNiuException("单据明细错误：不能修改其他单据的明细记录");
            oldVAreaCalculationMain = getById(mainId);
            Integer voucherState = oldVAreaCalculationMain.getVoucherState();
            /**************  修改权限 *******************/
            if(!crmGoodsService.isHaveOperationRight(oldVAreaCalculationMain.getCreateUserId().longValue())){
                throw new NuoNiuException("你没有权限操作该记录");
            }
            if(null != voucherState && voucherState > 0){
                throw new NuoNiuException("已审核,不能修改");
            }

            areaCalculationMain.setUpdateUserId(userInfo.getUserId());
            areaCalculationMain.setUpdateUserName(userInfo.getRealName());
            areaCalculationMain.setAccountId(oldVAreaCalculationMain.getAccountId());
            areaCalculationMain.setSourceVoucherId(oldVAreaCalculationMain.getSourceVoucherId());
            areaCalculationMain.setSourceVoucherCode(oldVAreaCalculationMain.getSourceVoucherCode());
            areaCalculationMain.setSourceVoucherType(oldVAreaCalculationMain.getSourceVoucherType());
            areaCalculationMain.setSourceVoucherDate(oldVAreaCalculationMain.getSourceVoucherDate());
            //不可更新字段
            areaCalculationMain.setVoucherCode(null);

        }else{
            String code = getCode();
            if(StringUtils.isBlank(code)) {
                throw new NuoNiuException("单据编码今日已上限");
            }
            /** 查询 第一条 工艺路线*/
            Page<ErpProcessRoute> page = erpProcessRouteService.getList(new Page(), new ErpProcessRoute());
            if(page.getSize() == 0)throw new NuoNiuException("请配置工艺路线");
            List<ErpProcessRoute> records = page.getRecords();
            ErpProcessRoute erpProcessRoute = records.get(0);
            areaCalculationMain.setProcessRouteId(erpProcessRoute.getId().intValue());
            areaCalculationMain.setProcessRouteName(erpProcessRoute.getName());
            //校验详情（详情不能有ID）
            boolean isHaveId = orderDetailList.stream().anyMatch(f -> null != f.getId());
            if(isHaveId)throw new NuoNiuException("单据明细错误：不能新增已经存在的明细记录");
            areaCalculationMain.setCompanyId(userInfo.getCompanyId());
            areaCalculationMain.setVoucherCode(code);
            areaCalculationMain.setAccountId(accountService.getCurrentAccountId());
            areaCalculationMain.setCreateUserId(userInfo.getUserId());
            areaCalculationMain.setCreateUserName(userInfo.getRealName());
        }

        //不更新 累计执行数量
        areaCalculationMain.setCumExecuteQuantity(null);
        // 校验 明细数量
        boolean isOk = areaCalculationMain.getOrderDetailList().stream().anyMatch(f -> null == f.getQuantity() || !(f.getQuantity().compareTo(BigDecimal.ZERO) > 0));
        if(isOk)throw new NuoNiuException("明细数量必须大于0");
        //计算 明细物料 总数
        BigDecimal totalQuantity =  areaCalculationMain.getOrderDetailList().stream().map(VAreaCalculationDetail::getQuantity).reduce(BigDecimal.ZERO,BigDecimal::add);
        areaCalculationMain.setTotalQuantity(totalQuantity.abs());
        boolean result = saveOrUpdate(areaCalculationMain);
        if(result) {
            List<Long> detailIds = new ArrayList<>();
            orderDetailList.forEach(p -> {
                p.setOrderId(areaCalculationMain.getId().intValue());
                p.setCompanyId(userInfo.getCompanyId());
                p.setAccountId(areaCalculationMain.getAccountId());
                p.setSourceVoucherCode(areaCalculationMain.getSourceVoucherCode());
                p.setSourceVoucherId(areaCalculationMain.getSourceVoucherId());
                p.setSourceVoucherType(areaCalculationMain.getSourceVoucherType());
                p.setSourceVoucherDate(areaCalculationMain.getSourceVoucherDate());
                if (p.getId() != null) {
                    detailIds.add(p.getId());
                }
            });

            if (null != mainId) {
                //删除明细
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("order_id", mainId);
                if (detailIds != null && detailIds.size() > 0) {
                    wrapper.notIn("id", detailIds);
                }
                areaCalculationDetailService.remove(wrapper);
            }
            //保存单据明细表
            areaCalculationDetailService.saveOrUpdateBatch(orderDetailList);
        }
        /** 根据指定规则 生成条码 */
        if ( null == mainId ){
            generateAreaCalculationBarCodes(areaCalculationMain);
        }else{
            // todo  根据 修改 的明细 进行 条码生成 （根据后续 需求 变动）
        }

    }

    /**
     * 按照特定 规则 生产 条码（初次；保存到条码主档）
     * @param areaCalculationMain
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void generateAreaCalculationBarCodes(VAreaCalculationMain areaCalculationMain) {
        LocalDateTime now = LocalDateTime.now();
        Long areaCalculationMainId = areaCalculationMain.getId();
        /**  动态属性：表头 */
        String voucherCode = areaCalculationMain.getVoucherCode();
        String projectCode = areaCalculationMain.getProjectCode();
        String batch = areaCalculationMain.getBatch();

        /** 校验是否存在 指定 来源单据的 记录 */
        barcodeMainInfoService.checkSourceVoucherType(areaCalculationMainId.intValue(),"AreaCalculation");

        /** 生成 指定规则 的条码 */
        List<ErpBarcodeMainInfo> erpBarcodeMainInfoList = new ArrayList<>();
        List<VAreaCalculationDetail> orderDetailList = areaCalculationMain.getOrderDetailList();

        for (int i = 0; i < orderDetailList.size(); i++) {
            VAreaCalculationDetail areaCalculationDetail = orderDetailList.get(i);
            ErpBarcodeMainInfo erpBarcodeMainInfo = new ErpBarcodeMainInfo();
            /**  动态属性：明细 */
            String no = areaCalculationDetail.getNo();
            String colorName = areaCalculationDetail.getColorName();
            String lineNumber = areaCalculationDetail.getLineNumber();
            BigDecimal quantity = areaCalculationDetail.getQuantity();
            int quantityIntValue = quantity.intValue();
            Integer sort = 1;

            BeanUtils.copyProperties(areaCalculationDetail,erpBarcodeMainInfo);
            /** 组装动态属性 */
            Map<String,Object> extendJsonMap = new HashMap<>();
            extendJsonMap.put("voucherCode",voucherCode);
            extendJsonMap.put("projectCode",projectCode);
            extendJsonMap.put("batch",batch);
            extendJsonMap.put("no",no);
            extendJsonMap.put("colorName",colorName);
            extendJsonMap.put("lineNumber",lineNumber);
            extendJsonMap.put("quantity",quantityIntValue);
            extendJsonMap.put("sort",sort);
            String extendJson = JSONObject.toJSONString(extendJsonMap);
            erpBarcodeMainInfo.setExtendJson(extendJson);
            /**  条码规则： 产品编号 + 行号 */
            String bacCode = no +"*"+ lineNumber;
            erpBarcodeMainInfo.setBarCode(bacCode);
            erpBarcodeMainInfo.setSourceVoucherId(areaCalculationMainId.intValue());
            erpBarcodeMainInfo.setSourceVoucherCode(voucherCode);
            erpBarcodeMainInfo.setSourceVoucherType("AreaCalculation");
            erpBarcodeMainInfo.setSourceDetailId(areaCalculationDetail.getId().intValue());
            erpBarcodeMainInfo.setSourceVoucherDate(now.toLocalDate());
            erpBarcodeMainInfo.setId(null);
            erpBarcodeMainInfo.setBaseQuantity(BigDecimal.ONE);

            quantityIntValue++;
            for (int j = 1; j < quantityIntValue ; j++) {
                ErpBarcodeMainInfo childErpBarcodeMainInfo = new ErpBarcodeMainInfo();
                BeanUtils.copyProperties(erpBarcodeMainInfo,childErpBarcodeMainInfo);
                /** 重新 设置条码 */
                childErpBarcodeMainInfo.setBarCode(bacCode + "*" + j);
                /** 重新 设置条码动态解析JSON */
                extendJsonMap.put("sort",j);
                String childExtendJson = JSONObject.toJSONString(extendJsonMap);
                childErpBarcodeMainInfo.setExtendJson(childExtendJson);
                erpBarcodeMainInfoList.add(childErpBarcodeMainInfo);
            }
        }
        /** 保存 条码主档 */
        boolean saveMainInfoBatch = barcodeMainInfoService.saveBatch(erpBarcodeMainInfoList);
    }

    @Override
    public String getCode() {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = erpAccountService.getCurrentAccountId();
        ErpNumberSet numberSet = numberSetMapper.getByCode("AreaCalculation", userInfo.getCompanyId(), currentAccountId);
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }

    @Override
    public void examine(Long id, Integer status) {
        if(null == id || null == status || (null != status && (status > 1 || status < 0)))throw new NuoNiuException("参数错误");
        UserInfo userInfo = UserThreadLocal.get();
        VAreaCalculationMain areaCalculationMain = getById(id);
        if(!userInfo.getCompanyId().equals(areaCalculationMain.getCompanyId()))throw new NuoNiuException("cId参数错误");
        if(areaCalculationMain == null) {
            throw new NuoNiuException("单据不存在");
        }
        areaCalculationMain.setVoucherState(status);
        areaCalculationMain.setReviewerDate(LocalDateTime.now());
        areaCalculationMain.setReviewerUserId(userInfo.getUserId());
        areaCalculationMain.setReviewerUserName(userInfo.getRealName());
        updateById(areaCalculationMain);

        /** 审核通过 自动 生产 物料分类 和 物料档案*/


    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteById(Long id) {
        VAreaCalculationMain areaCalculationMain = getById(id);
        if(areaCalculationMain == null) {
            throw new NuoNiuException("单据已删除");
        }
        /**************  修改权限 *******************/
        if(!crmGoodsService.isHaveOperationRight(areaCalculationMain.getCreateUserId().longValue())){
            throw new NuoNiuException("你没有权限操作该记录");
        }
        BigDecimal cumExecuteQuantity = areaCalculationMain.getCumExecuteQuantity();
        if(null != cumExecuteQuantity && cumExecuteQuantity.compareTo(BigDecimal.ZERO) > 0){
            throw new NuoNiuException("单据已生单，不能删除");
        }
        removeById(id);
        areaCalculationDetailService.removeByOrderId(id);

    }

    @Override
    public VAreaCalculationMain importData(MultipartFile file) throws NoSuchFieldException, IOException {
        log.debug("==============导入开始=============" + LocalDateTime.now());
        List<VAreaCalculationDetail> calculationDetails = new ArrayList<>();
        String[] filed = {"lineNumber", "no", "quantity", "length", "width", "unitArea", "totalArea", "cuttingSizeLength", "cuttingSizeWidth", "colorName", "panel", "template", "panelThickness", "weldLine",
                "grooving", "openNumber", "bendNumber"};
        Workbook wb;
        boolean isExcel2003 = true;
        if (file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        //解析excel
        InputStream is = file.getInputStream();
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        List<String> cellData = new ArrayList<>();
        Sheet sheet = wb.getSheetAt(3);
        log.debug("==============解析表头开始=============" + LocalDateTime.now());
        for (int r = 2; r < 4; r++) { //循环excel行读取表头数据
            Row row = sheet.getRow(r);
            for (int i = 0; i < filed.length; i++) {
                if(row.getCell(i) != null) {
                    row.getCell(i).setCellType(CellType.GREATER_THAN);
                    String cellValue = row.getCell(i).getStringCellValue().trim();
                    if(StringUtils.isNotBlank(cellValue)) {
                        cellData.add(cellValue);
                        System.out.println(cellValue);
                    }
                }
            }
        }

        log.debug("==============解析表头结束=============" + LocalDateTime.now());
        log.debug("==============解析明细开始=============" + LocalDateTime.now());
        for (int r = 5; r <= sheet.getLastRowNum(); r++) { //循环excel行读取明细数据
            VAreaCalculationDetail calculationDetail = new VAreaCalculationDetail(); //数据
            Row row = sheet.getRow(r);
            if(row == null || row.getCell(0) == null) {
                continue;
            }

            log.debug("解析明细第" + r + "行 开始========================" +  LocalDateTime.now());
            row.getCell(0).setCellType(CellType.GREATER_THAN);
            if(StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                continue;
            }

            for (int i = 0; i < filed.length; i++) {
                int k = i;

                if(i >= 7) {
                    k = i + 1;
                }

                if (row.getCell(k) == null || row.getCell(k).equals("*")) {
                    continue;
                }

                row.getCell(k).setCellType(CellType.GREATER_THAN);
                String cellValue = (row.getCell(k).getStringCellValue() + "").trim();
                Class crmCompanyClass = calculationDetail.getClass();
                Field f = crmCompanyClass.getDeclaredField(filed[i]);
                f.setAccessible(true);
                try {
                    //log.debug(cellValue);
                    if(StringUtils.isNotBlank(cellValue)) {
                        if(filed[i].equals("quantity") || filed[i].equals("length") || filed[i].equals("width") || filed[i].equals("unitArea") || filed[i].equals("totalArea")) {
                            f.set(calculationDetail, new BigDecimal(cellValue));
                        } else {
                            f.set(calculationDetail, cellValue);
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            if(calculationDetail != null || calculationDetail.getQuantity() == null) {
                calculationDetails.add(calculationDetail);
            }
            log.debug("解析明细第" + r + "行 结束========================" +  LocalDateTime.now());
        }

        log.debug("==============解析明细结束=============" + LocalDateTime.now());
        VAreaCalculationMain calculationMain = new VAreaCalculationMain();
        calculationMain.setProjectCode(cellData.get(3));
        calculationMain.setProjectName(cellData.get(1));
        ErpProject project = projectService.getByName(calculationMain.getProjectName());
        if(project != null) {
            calculationMain.setProjectId(project.getId().intValue());
            calculationMain.setProjectCode(project.getCode());
        }

        calculationMain.setBatch(cellData.get(5));
        calculationMain.setCalculationUserName(cellData.get(8));
        SysUser user = userService.getByRealName(calculationMain.getCalculationUserName());
        if(user != null) {
            calculationMain.setCalculationUserId(user.getId().intValue());
        }
        LocalDate voucherDate = LocalDate.parse(cellData.get(10), DateTimeFormatter.ofPattern("yyyy.MM.dd"));
        calculationMain.setVoucherDate(voucherDate);
        calculationMain.setEdition(cellData.get(12));
        calculationMain.setCustomerOrderNumber(cellData.get(13));
        calculationMain.setOrderDetailList(calculationDetails);
        log.debug("==============导入结束=============" + LocalDateTime.now());
        return calculationMain;
    }

    @Override
    public void exportData(HttpServletResponse response, Integer orderId) {
        UserInfo userInfo = UserThreadLocal.get();
        String fileName = "面积计算表导出数据.xls";
        List<HashMap<String, Object>> data = baseMapper.getList(userInfo.getCompanyId(), orderId);
        Object[] title = {"编号", "单价", "数量", "长(L)", "宽(W)", "单件面积(㎡)", "合计面积(㎡)", "开料尺寸长", "开料尺寸宽", "颜色", "板材", "板厚", "板型", "焊缝(米)", "刨槽(米)", "开孔个数", "折弯刀数"};
        String[] exportFiled = {"no", "price", "quantity", "length", "width", "unit_area", "total_area", "cutting_size_length", "cutting_size_width", "color_name", "panel", "template", "panel_thickness", "weld_line",
                "grooving", "open_number", "bend_number"};
        ExcelUtils.exportData(title,  fileName, data, exportFiled, response);
    }

    @Override
    public void setPrice(VAreaCalculationMain areaCalculationMain) {
        Long id = areaCalculationMain.getId();
        VAreaCalculationMain findVAreaCalculationMain = getById(id);
        if(null == findVAreaCalculationMain)throw new NuoNiuException("查询不要记录");
        Integer voucherState = findVAreaCalculationMain.getVoucherState();
        if(voucherState == 10)throw new NuoNiuException("单据已经关闭，不能再挂价了");
        List<VAreaCalculationDetail> areaCalculationDetails = areaCalculationMain.getOrderDetailList();
        UserInfo userInfo = UserThreadLocal.get();
        if (null == areaCalculationDetails || areaCalculationDetails.size() == 0)throw new NuoNiuException("数据不能为空");
        Map<Long,VAreaCalculationDetail> areaCalculationDetailMap = new HashMap<>();
        Set<Long> ids = new LinkedSet<>();
        for (int i = 0; i < areaCalculationDetails.size(); i++) {
            VAreaCalculationDetail areaCalculationDetail = areaCalculationDetails.get(i);
            Long detailId = areaCalculationDetail.getId();
            if(null != detailId){
                ids.add(detailId);
                areaCalculationDetailMap.put(detailId,areaCalculationDetail);
            }
        }
        QueryWrapper<VAreaCalculationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.in("id",ids);
        queryWrapper.select("id");
        List<VAreaCalculationDetail> findList = areaCalculationDetailService.list(queryWrapper);

        List<Long> findIds = findList.stream().map(VAreaCalculationDetail::getId).collect(Collectors.toList());
        List<VAreaCalculationDetail> findVAreaCalculationDetails = new ArrayList<>();
        for (int i = 0; i < findIds.size(); i++) {
            Long detailId = findIds.get(i);
            VAreaCalculationDetail areaCalculationDetail = areaCalculationDetailMap.get(detailId);
            VAreaCalculationDetail newVAreaCalculationDetail = new VAreaCalculationDetail();
            newVAreaCalculationDetail.setId(detailId);
            newVAreaCalculationDetail.setPrice(areaCalculationDetail.getPrice());
            newVAreaCalculationDetail.setAmount(areaCalculationDetail.getAmount());

            findVAreaCalculationDetails.add(newVAreaCalculationDetail);
        }
        if(findVAreaCalculationDetails.size() > 0){
            areaCalculationDetailService.saveOrUpdateBatch(findVAreaCalculationDetails);
        }
    }

    @Override
    public void updateCumExecuteQuantity(Long mainId, BigDecimal addNum) {
        UserInfo userInfo = UserThreadLocal.get();
        baseMapper.updateCumExecuteQuantity(mainId,addNum,userInfo.getCompanyId());
    }

    @Override
    public List<ProjectExecutionStatisticsVo> projectExecutionStatistics(ProjectExecutionStatisticsDto projectExecutionStatisticsDto) {
        UserInfo userInfo = UserThreadLocal.get();
        List<ProjectExecutionStatisticsVo> projectExecutionStatisticsVos = baseMapper.projectExecutionStatistics(userInfo.getCompanyId(), projectExecutionStatisticsDto);
        return projectExecutionStatisticsVos;
    }

    @Override
    public List<VAreaCalculationMain> areaCalculationMainStatistics(Integer projectId) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<VAreaCalculationMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("project_id",projectId);
        List<VAreaCalculationMain> areaCalculationMainList = list(queryWrapper);
        Map<Long,List<ProjectBatchExecutionStatisticsVo>> areaCalculationMainMap = new HashMap<>();
        for (int i = 0; i < areaCalculationMainList.size(); i++) {
            VAreaCalculationMain areaCalculationMain = areaCalculationMainList.get(i);
            List<ProjectBatchExecutionStatisticsVo> projectBatchExecutionStatisticsVos = new ArrayList<>();
            areaCalculationMain.setProjectBatchExecutionStatisticsVos(projectBatchExecutionStatisticsVos);
            areaCalculationMainMap.put(areaCalculationMain.getId(),projectBatchExecutionStatisticsVos);
        }
        List<ProjectBatchExecutionStatisticsVo> projectBatchExecutionStatisticsVos = baseMapper.ProjectBatchExecutionStatistics(userInfo.getCompanyId(), projectId);
        for (int i = 0; i < projectBatchExecutionStatisticsVos.size(); i++) {
            ProjectBatchExecutionStatisticsVo statisticsVo = projectBatchExecutionStatisticsVos.get(i);
            Long mainId = statisticsVo.getId();
            List<ProjectBatchExecutionStatisticsVo> findArray = areaCalculationMainMap.get(mainId);
            if(null != findArray){
                findArray.add(statisticsVo);
            }
        }
        return areaCalculationMainList;
    }

    @Override
    public VAreaCalculationMain getBatchExecutionStatisticsVos(Integer mainId) {
        UserInfo userInfo = UserThreadLocal.get();
        VAreaCalculationMain calculationMain = getById(mainId);
        List<ProjectBatchExecutionStatisticsVo> projectBatchExecutionStatisticsVos = baseMapper.ProjectBatchExecutionStatisticsFromMainId(userInfo.getCompanyId(), mainId);
        calculationMain.setProjectBatchExecutionStatisticsVos(projectBatchExecutionStatisticsVos);
        BarcodeInOutStatisticVo areaCalculation = barcodeInOutService.getBatchInOutRecord(userInfo.getCompanyId(), "AreaCalculation", mainId);
        calculationMain.setBarcodeInOutStatisticVo(areaCalculation);
        return calculationMain;
    }

    @Override
    public VAreaCalculationMain analysisByBarCode(String barcode, Integer businessType) {
        BarcodeMainInfoSearchDto barcodeMainInfoSearchDto = new BarcodeMainInfoSearchDto();
        barcodeMainInfoSearchDto.setBusinessType(businessType);
        barcodeMainInfoSearchDto.setBarcode(barcode);
        List<VAreaCalculationDetail> vAreaCalculationDetails = areaCalculationDetailService.analysisByBarCode(barcodeMainInfoSearchDto);
        if (vAreaCalculationDetails.size() == 0)return null;
        VAreaCalculationDetail areaCalculationDetail = vAreaCalculationDetails.get(0);
        VAreaCalculationMain areaCalculationMain = getById(areaCalculationDetail.getOrderId());
        areaCalculationMain.setOrderDetailList(vAreaCalculationDetails);
        return areaCalculationMain;
    }

    @Override
    public void importPrice(Integer orderId, MultipartFile file) throws IOException {
        Workbook wb;
        boolean isExcel2003 = true;
        if (file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        //解析excel
        InputStream is = file.getInputStream();
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        List<VAreaCalculationDetail> details = new ArrayList<>();
        Sheet sheet = wb.getSheetAt(0);
        for (int r = 1; r <= sheet.getLastRowNum(); r++) { //循环excel行读取表头数据
            Row row = sheet.getRow(r);
            if(row == null || row.getCell(0) == null) {
                continue;
            }

            row.getCell(0).setCellType(CellType.GREATER_THAN);
            row.getCell(1).setCellType(CellType.GREATER_THAN);
            String no = row.getCell(0).getStringCellValue(); //产品名称
            String price = row.getCell(1).getStringCellValue(); //产品价格
            if(StringUtils.isNotBlank(no) && StringUtils.isNotBlank(price)) {
                VAreaCalculationDetail detail = new VAreaCalculationDetail();
                detail.setOrderId(orderId);
                detail.setNo(no);
                detail.setPrice(new BigDecimal(price));
                details.add(detail);
            }
        }

        //批量修改
        baseMapper.updatePrice(details);
    }

    @Override
    public void autoGenerateInventory(Long id) {
        UserInfo userInfo = UserThreadLocal.get();
        /** 1. 获取 面积计算表 明细 */
        VAreaCalculationMain areaCalculationMain = getById(id);
        List<VAreaCalculationDetail> vAreaCalculationDetails = areaCalculationDetailService.listByMainId(id);
        /** 2. 根据明细 生成 物料档案 */
        for (VAreaCalculationDetail areaCalculationDetail: vAreaCalculationDetails){
            InInventory inventory = new InInventory();
            InInventorySaveDto inInventorySaveDto = new InInventorySaveDto();
            inInventorySaveDto.setInInventory(inventory);
            inventory.setInventoryName(areaCalculationDetail.getNo());
            inInventoryService.saveInInventory(inInventorySaveDto);
        }

    }

}
